package com.ukefu.webim.service.sms;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.ukefu.util.HttpClientUtil;
import com.ukefu.util.UKTools;
import com.ukefu.util.sms.SmsService;
import com.ukefu.webim.web.model.SmsResult;
import com.ukefu.webim.web.model.SmsTemplate;
import com.ukefu.webim.web.model.SystemMessage;

@Service("postsms")
public class PostSmsImpl implements SmsService {

	@Override
	public SmsResult send(SystemMessage systemMessage, SmsResult result, String phone, SmsTemplate tp, Map<String, Object> values)
			throws Exception {
		try {
			if(values == null) {
				values = new HashMap<String,Object>();
			}
			values.put("appkey", systemMessage.getAppkey()) ;
			values.put("appsec", systemMessage.getAppsec()) ;
			String time = UKTools.simpleDateFormat2.format(new Date());
			values.put("code", systemMessage.getAppkey()) ;
			values.put("md5", UKTools.localMd5(systemMessage.getAppsec())) ;
			values.put("sign", UKTools.localMd5(systemMessage.getAppsec()+time)) ;
			values.put("timestamp", time) ;
			values.put("mobile", phone) ;
//			values.put("content", phone) ;
			
			String body = UKTools.getTemplet(tp.getTemplettext(),values) ;
			String checkstr = systemMessage.getResultcheck() ;
			if(StringUtils.isBlank(checkstr)) {
				checkstr = "true" ;
			}
			result.setSmstext(body);
			result.setSendresult(HttpClientUtil.sendHttpPostJson(systemMessage.getUrl(),body));
			if(!StringUtils.isBlank(result.getSendresult()) && result.getSendresult().indexOf(checkstr) >= 0) {
				result.setSendok(true);
			}
		} catch (Exception ex) {
			result.setSendresult(ex.getMessage());
			throw ex;
		} finally {
			result.setSendtime(new Date());
		}
		return result;
	}

	@Override
	public SmsResult checkReach(SmsResult result) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
